package com.sdp.right.control;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.exception.ExceptionMessage;
import com.sdp.core.bizc.redis.RedisUtil;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.db.sys_page.service.ISysPageService;
import com.sdp.right.entity.SysPage;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2023-10-31
 */
@RestController
@RequestMapping("/SysPageController")
@Slf4j
public class SysPageController {

	@Autowired
	private ISysPageService iSysPageService;
	
	@Autowired
	private Query query;
	
	@Autowired
	HttpServletRequest request;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private RedisUtil redisUtil;
		
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iSysPageService, SysPage.class, dataCenter));
	}
	
	@GetMapping(value = "/querySysPageById")
	public Result<?> querySysPageById(@RequestParam(name="pageId",required=true) String pageId) {
		if(StringUtils.isEmpty(pageId) || StringUtils.isEmpty(pageId)) {
			return Result.error("页面内码不存在");
		}
		// 先从缓存查询
		Object redisPage = redisUtil.getMap(SysPage.class, pageId);
		if(StringUtils.isEmpty(redisPage) || "{}".equals(redisPage.toString())) {
			SysPage page = iSysPageService.querySysPageById(pageId);
			redisUtil.setMap(SysPage.class, pageId, page);
			redisPage = page;
		}
		return Result.ok(redisPage);
	}
	
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody SysPage sysPage) {
		if(sysPage==null) {
			return Result.error("页面信息不存在");
		}
		if(StringUtils.isEmpty(sysPage.getKeyId())) {
			sysPage.setCreateTime(LocalDateTime.now());
			Result<?> r = uniqueCheckTools.isUniqueSingle(iSysPageService, SysPage.class, new String[] {"pageName"}, "keyId",sysPage, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("页面名称不能重复");
			}
			iSysPageService.save(sysPage);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iSysPageService, SysPage.class, new String[] {"pageName"}, "keyId",null, sysPage, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("页面名称不能重复");
			}
			iSysPageService.updateById(sysPage);
		}
		redisUtil.del(SysPage.class, sysPage.getKeyId());
		return Result.ok(sysPage);
	}
	

	@GetMapping(value = "/del")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> del(@RequestParam(name="keyId",required=true) String keyId) {
		if(StringUtils.isEmpty(keyId)) {
			return Result.error("页面编码不存在,不能删除");
		}
		iSysPageService.removeSysPageByPageId(keyId);
		redisUtil.del(SysPage.class,keyId);
		return Result.ok();
	}
	
	
	@GetMapping(value = "/clone")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> clone(@RequestParam(name="keyId",required=true) String keyId) {
		if(StringUtils.isEmpty(keyId)) {
			return Result.error("页面编码不存在,不能复制");
		}
		SysPage sysPage = iSysPageService.getById(keyId);
		sysPage.setKeyId(null);
		sysPage.setPageName(sysPage.getPageName()+"_复制");
		sysPage.setCreateTime(LocalDateTime.now());
		iSysPageService.save(sysPage);
		return Result.ok();
	}
	
	@PostMapping(value = "/pageImport")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> pageImport(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
		if (StringUtils.isEmpty(mf) || !mf.getOriginalFilename().endsWith(".txt")) {
			return Result.error("仅支持TXT文件上传");
		}
		String fileContent;
		
		try {
			InputStream fileContentStream = mf.getInputStream();
			 BufferedReader reader = new BufferedReader(new InputStreamReader(fileContentStream, StandardCharsets.UTF_8));
		     fileContent = reader.lines().collect(Collectors.joining(System.lineSeparator()));
		     SysPage page = JSONObject.toJavaObject(JSON.parseObject(fileContent), SysPage.class);
		     page.setCreateTime(LocalDateTime.now());
		     SysPage dbPage = iSysPageService.querySysPageById(page.getKeyId());
		     if(dbPage!=null) {
		    	return Result.error("页面内码重复，不能导入");
		     }
		     iSysPageService.save(page);
		} catch (Exception e) {
			log.error(ExceptionMessage.getExceptionMessage(e));
		}
       
		return Result.ok();
	}
}

